package com.atguigu.srb.core.service.impl;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.enums.UserBindEnum;
import com.atguigu.srb.core.hfb.FormHelper;
import com.atguigu.srb.core.hfb.HfbConst;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.mapper.UserAccountMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.UserAccount;
import com.atguigu.srb.core.pojo.entity.UserBind;
import com.atguigu.srb.core.mapper.UserBindMapper;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.vo.UserBindVO;
import com.atguigu.srb.core.service.UserBindService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 服务实现类
 * </p>
 *
 * @author DaYouZi
 * @since 2022-12-01
 */
@Service
public class UserBindServiceImpl extends ServiceImpl<UserBindMapper, UserBind> implements UserBindService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private UserAccountMapper userAccountMapper;

    /**
     * 账户绑定提交到托管平台的数据
     */
    @Override
    public String commitBindUser(UserBindVO userBindVO, Long userId) {

        //查询身份证号是否已存在，或已经被其他用户使用
        UserBind userBind = baseMapper.selectOne(new QueryWrapper<UserBind>()
                .eq("id_card", userBindVO.getIdCard())
                .ne("user_id", userId));

        Assert.isNull(userBind, ResponseEnum.USER_BIND_IDCARD_EXIST_ERROR);

        //查询用户之前进行过的绑定信息（可能存在，也可能不存在）
        userBind = baseMapper.selectOne(new QueryWrapper<UserBind>()
                .eq("user_id", userId));
        if (userBind == null) {
            //用户之前不存在绑定记录，则新增一条绑定记录
            userBind = new UserBind();
            BeanUtils.copyProperties(userBindVO, userBind);
            userBind.setUserId(userId);
            userBind.setStatus(UserBindEnum.NO_BIND.getStatus());
            baseMapper.insert(userBind);
        } else {
            //用户之前存在绑定记录，但是之前的操作可能没完成，故将用户新填写的信息同步到userBind
            BeanUtils.copyProperties(userBindVO, userBind);
            baseMapper.updateById(userBind);
        }

        //构建表单信息，发送至hfb进行绑定（hfb必须接收表单信息）
        Map<String, Object> paramMap = new HashMap<>();
        //填充基本信息
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentUserId", userId);
        paramMap.put("idCard", userBindVO.getIdCard());
        paramMap.put("personalName", userBindVO.getName());
        paramMap.put("bankType", userBindVO.getBankType());
        paramMap.put("bankNo", userBindVO.getBankNo());
        paramMap.put("mobile", userBindVO.getMobile());
        //填充用户绑定同步回调
        paramMap.put("returnUrl", HfbConst.USERBIND_RETURN_URL);
        //填充用户绑定异步回调
        paramMap.put("notifyUrl", HfbConst.USERBIND_NOTIFY_URL);
        //填充时间戳
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        //填充表单请求数据加密签名
        paramMap.put("sign", RequestHelper.getSign(paramMap));

        //构建自动提交form表单
        return FormHelper.buildForm(HfbConst.USERBIND_URL, paramMap);
    }


    /**
     * 更新用户绑定状态
     * @param paramMap
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void notifys(Map<String, Object> paramMap) {

        String bindCode = (String)paramMap.get("bindCode");
        String userId = (String)paramMap.get("agentUserId");

        //新增user_account账户
        UserAccount userAccount = userAccountMapper.selectOne(new QueryWrapper<UserAccount>().eq("user_id", userId));
        if(null == userAccount) {
            userAccount =  new UserAccount();
            userAccount.setUserId(Long.parseLong(userId));
            userAccount.setAmount(new BigDecimal("0"));
            userAccount.setFreezeAmount(new BigDecimal("0"));
            userAccountMapper.insert(userAccount);
        }

        //更新user_bind表
        UserBind userBind = baseMapper.selectOne(new QueryWrapper<UserBind>().eq("user_id", userId));
        userBind.setBindCode(bindCode);
        userBind.setStatus(UserBindEnum.BIND_OK.getStatus());
        baseMapper.updateById(userBind);

        //更新user_info表
        UserInfo userInfo = userInfoMapper.selectById(userId);
        userInfo.setBindCode(bindCode);
        userInfo.setName(userBind.getName());
        userInfo.setIdCard(userBind.getIdCard());
        userInfo.setBindStatus(UserBindEnum.BIND_OK.getStatus());
        userInfoMapper.updateById(userInfo);
    }


    /**
     * 获取投资人的绑定协议号
     * @param userId
     * @return
     */
    @Override
    public String getBindCodeByUserId(Long userId) {
        UserBind userBind = baseMapper.selectOne(new QueryWrapper<UserBind>()
                .eq("user_id", userId));
        return userBind.getBindCode();
    }
}
